package controllers

import (
	"github.com/astaxie/beego"
	"travelservia/models"
	"HTtravelservia/htmodels"
	"strconv"
	"time"
	"os"
	"strings"
	"github.com/astaxie/beego/validation"
)

type XiangmuController struct {
	beego.Controller
}

//带了参数导致bootstrap table无法正常使用
func (c *XiangmuController)HTXiangmuList_html() {
	str_Status := c.Ctx.Input.URL()[strings.LastIndex(c.Ctx.Input.URL(), "/") + 1:]
	Status, _ := strconv.Atoi(str_Status)
	c.Data["Status"] = Status
	c.TplName = "xiangmu_list.html"
	c.Render()
}

func (c *XiangmuController)HTXiangmuList() {
	Status, _ := c.GetInt("Status")
	limit, _ := c.GetInt("limit")
	offset, _ := c.GetInt64("offset")
	orderby := ""
	if order := c.GetString("order"); order != "asc" {
		orderby += "-"
	}
	orderfiled := c.GetString("sort")
	orderby += orderfiled
	if orderfiled == "" {
		orderby = "-Id"
	}
	search := c.GetString("search")
	fileds := []string{ "Id", "Title", "BasicPrice", "PublishTime", "EditTime", "WatchCount", "StarCount", "HotStatus"}
	Xiangmu := []models.Xiangmu{}
	htmodels.HTXiangmuGetList(&Xiangmu, fileds, Status,  offset, limit, search, "Title", orderby)
	count, _ := htmodels.HTXiangmuGetCount(search, "Title", Status, )
	c.Data["json"] = map[string]interface{}{"rows":&Xiangmu, "total":count}
	c.ServeJSON()
}


func (c *XiangmuController)HTXiangmuDetail() {
	Id, _ := c.GetInt64("Id")
	if Id != 0 {
		c.Data["update"] = true
		SetXiangmuDetailInfo(c, Id)
	}
	c.TplName = "xiangmu_detail.html"
}

func SetXiangmuDetailInfo(c *XiangmuController, Id int64) {
	Xiangmu := models.Xiangmu{Id:int(Id)}
	htmodels.HTXiangmuGetDetail(&Xiangmu)
	c.Data["Xiangmu"] = &Xiangmu
}

func (c *XiangmuController)HTXiangmuAdd() {
	Xiangmu := models.Xiangmu{}
	if err := c.ParseForm(&Xiangmu); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	Xiangmu.PublishTime = time.Now()
	Xiangmu.EditTime = time.Now()
	valide := validation.Validation{}
	if b, err := valide.Valid(&Xiangmu); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTXiangmuAdd(&Xiangmu); err != nil {
		Message(&c.Controller, "", "添加失败，即将返回！" + err.Error(), "", true)
	}
	path:="/var/uploads/travelservia"
	url:= "uploads/Xiangmu/ListPic"
	if strings.Index(url, "?") != -1 {
		url = url[:strings.Index(url, "?")]
	}
	totalpath := path + url[strings.Index(url, "uploads") + len("uploads"):]
	GenerateTumbnail(totalpath, "Xiangmu", int64(Xiangmu.Id), 100, 100)
	Message(&c.Controller, `/xiangmu/detail`, "添加成功！", "", false)
}


func (c *XiangmuController)HTXiangmuUpdate() {
	Id , _ := c.GetInt64("Id");
	Xiangmu := models.Xiangmu{Id:int(Id)}
	if err:=htmodels.HTXiangmuGetDetail(&Xiangmu);err!=nil{
		Message(&c.Controller, "", "严重错误，请联系管理员,即将返回！" + err.Error(), "", true)
	}
	if err := c.ParseForm(&Xiangmu); err != nil {
		Message(&c.Controller, "", "输入数据不对,即将返回！" + err.Error(), "", true)
	}
	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("publishtime"));err!=nil{
		Xiangmu.PublishTime=time.Now()
	}else{
		Xiangmu.PublishTime=time_up
	}

	if time_up, err := time.Parse("2006-01-02 15:04:05", c.GetString("edittime"));err!=nil{
		Xiangmu.EditTime=time.Now()
	}else{
		Xiangmu.EditTime=time_up
	}

	valide := validation.Validation{}
	if b, err := valide.Valid(&Xiangmu); !b || err != nil {
		if !b {
			Message(&c.Controller, "", "数据验证失败，即将返回！", "", true)
		}
		if err != nil {
			Message(&c.Controller, "", "数据验证错误，即将返回！" + err.Error(), "", true)
		}
	}
	if err := htmodels.HTXiangmuUpdate(&Xiangmu); err != nil {
		Message(&c.Controller, "", "更新失败，即将返回！" + err.Error(), "", true)
	}
	Message(&c.Controller, `/xiangmu/list_html`+`/`+strconv.Itoa(Xiangmu.Status), "更新成功！", "", false)
}


func (c *XiangmuController)HTXiangmuDelete() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	count, err := htmodels.HTXiangmuDelete(Ids)
	if err != nil {
		Json_Message(&c.Controller, 0, "删除失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "删除" + strconv.FormatInt(count, 10) + "行")
}


func (c *XiangmuController)HTXiangmuStatusChange() {
	Ids := make([]int64, 0, 100)
	c.Ctx.Input.Bind(&Ids, "Id")
	Status, err1 := c.GetInt("ChangedStatus")
	if err1 != nil {
		Json_Message(&c.Controller, 0, "更改失败")
	}
	count, err := htmodels.HTXiangmuStatusChange(Ids, Status)
	if err != nil {
		Json_Message(&c.Controller, 0, "更改失败" + err.Error())
	}
	Json_Message(&c.Controller, 1, "更改" + strconv.FormatInt(count, 10) + "行状态")
}


//image upload
func (c *XiangmuController)HTXiangmuPicUp() {
	Id, _ := c.GetInt64("Id")
	_, h, err := c.GetFile("Filedata")
	if err != nil {
		Json_Message(&c.Controller, 1, "file upload error")
	}
	url := c.GetString("imagepath")
	totalpath := ""
	path := beego.AppConfig.String("uploadspath")
	if url == "" {
		typename := h.Filename[strings.LastIndex(h.Filename, "."):]
		date := time.Now().Format("2006-01-02")
		directory := "/xiangmu/pics/" + date
		filename := RandString(8)
		totalpath = path + directory + "/" + filename + typename
		url = "/uploads" + directory + "/" + filename + typename
		os.MkdirAll(path + directory, 0777)
	} else {
		if strings.Index(url, "?") != -1 {
			url = url[:strings.Index(url, "?")]
		}
		totalpath = path + url[strings.Index(url, "uploads") + len("uploads"):]
	}

	if err := c.SaveToFile("Filedata", totalpath); err != nil {
		Json_Message(&c.Controller, 1, "file save error" + err.Error())
	}
	if Id != 0 {
		GenerateTumbnail(totalpath, "Xiangmu", Id, 100, 100)
	}
	Json_Message(&c.Controller, 0, url + "?time=" + time.Now().String())
}

